package com.ruoyi.members.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.constant.CommonConstants;
import com.ruoyi.common.constant.MembersConstants;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.MembersStatus;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.members.domain.SysMembers;
import com.ruoyi.members.service.ISysMembersService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.members.mapper.UnionMembersMapper;
import com.ruoyi.members.service.UnionMembersService;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 会员Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-09-16
 */
@Service
public class UnionMembersServiceImpl extends ServiceImpl<UnionMembersMapper, SysMembers> implements UnionMembersService
{
    @Autowired
    private UnionMembersMapper unionMembersMapper;
    @Autowired
    private ISysMembersService sysMembersService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysRoleService sysRoleService;

    /**
     * 人才智库 - 会员管理 - 新增
     * @param sysMembers
     * @return
     */
    @Transactional
    @Override
    public MembersStatus saveMembers(SysMembers sysMembers) {
        //会员 - 工号不能重复 （会员表 工号字段）
        List<SysMembers> list = sysMembersService.list(new LambdaQueryWrapper<>(SysMembers.class)
                .eq(SysMembers::getMembersIsStatus, MembersConstants.IS_MEMBERS)
                .eq(SysMembers::getMembersNum, sysMembers.getMembersNum()));
        if (list.size() > 0){
            return MembersStatus.MEMBERS_NUM_EXIST;
        }
        //用户 - 账号不能重复 （用户表 账号字段）
        List<SysUser> list1 = sysUserService.list(new LambdaQueryWrapper<>(SysUser.class).eq(SysUser::getUserName, sysMembers.getMembersNum()));
        if (list1.size() > 0){
            return MembersStatus.USER_ACCOUNT_EXIST;
        }
        //会员 - 角色是否存在 (角色表 姓名字段)
        SysRole sysRole = new SysRole();
        sysRole.setRoleName(MembersConstants.UNION_MEMBERS_ROLE_NAME);
        List<SysRole> sysRoles = sysRoleService.selectRoleList(sysRole);
        if (sysRoles.size() == 0){
            return MembersStatus.UNION_MEMBERS_ROLE_NOT_EXIST;
        }


        //新增用户 用户表
        SysUser user = SysUser.builder()
                .userName(sysMembers.getMembersNum().toString())
                .nickName(sysMembers.getMembersName())
                .deptId(MembersConstants.NO_DEPT)
                .email(sysMembers.getMembersEmail())
                .phonenumber(sysMembers.getMembersTel())
                .sex(sysMembers.getMembersSex())
                .avatar(sysMembers.getMembersImg())
                .password(SecurityUtils.encryptPassword(CommonConstants.DEFAULT_PASSWORD))
                .build();
        user.setCreateBy(SecurityUtils.getUsername());
        boolean save = sysUserService.save(user);
        if (!save){
            return MembersStatus.USER_ADD_FAIL;
        }

        //新增会员（教职工表）
        sysMembers.setMembersIsStatus(MembersConstants.IS_MEMBERS);     //状态设置为会员状态
        sysMembers.setUserId(user.getUserId());
        sysMembers.setCreateBy(SecurityUtils.getUsername());
        sysMembers.setDeptId(MembersConstants.NO_DEPT);
        sysMembers.setSocietyId(MembersConstants.NO_ASSOCIATION);
        /**
         * 工会、协会
         */
        boolean save1 = sysMembersService.save(sysMembers);
        if (!save1){
            return MembersStatus.UNION_MEMBERS_ADD_FAIL;
        }

        //用户角色分配
        sysUserService.insertUserAuth(user.getUserId(), new Long[]{sysRoles.get(0).getRoleId()});


        return MembersStatus.SUCCESS;
    }


    /**
     * 人才智库 - 会员管理 - 删除
     */
    @Transactional
    @Override
    public MembersStatus deleteSysMembersByMemsIds(Long[] membersIds) {
        //TODO 判断会员是否存在，此处判断的是教职工，没有判断会员状态
        //查询教职工是否存在
        List<SysMembers> sysMembers = sysMembersService.listByIds(Arrays.asList(membersIds));
        if (sysMembers.size() == 0){
            return MembersStatus.UNION_MEMBERS_NOT_EXIST;
        }
        //删除会员
        boolean b = sysMembersService.removeByIds(Arrays.asList(membersIds));
        if (!b){
            return MembersStatus.UNION_MEMBERS_DELETE_FAIL;
        }
        //删除用户表
        List<Long> userIds = sysMembers.stream().map(members-> members.getUserId()).collect(Collectors.toList());
        boolean b1 = sysUserService.removeByIds(userIds);
        if (!b1){
            return MembersStatus.USER_DELETE_FAIL;
        }
        //删除用户角色表
        SysRole sysRole = new SysRole();
        sysRole.setRoleName(MembersConstants.UNION_MEMBERS_ROLE_NAME);
        List<SysRole> sysRoles = sysRoleService.selectRoleList(sysRole);
        //判断角色是否存在
        if (sysRoles.size() == 0){
            return MembersStatus.UNION_MEMBERS_ROLE_NOT_EXIST;
        }
        int i = sysRoleService.deleteAuthUsers(sysRoles.get(0).getRoleId(),userIds.toArray(new Long[0]));
        if (i == 0){
            return MembersStatus.ROLE_DELETE_FAIL;
        }
        return MembersStatus.SUCCESS;
    }
}
